#!/bin/bash


IP=192.168.200.30
PORT=35020
# NEWPORT=8547
# from account
FROMACCOUNT=8220f95f8db7bacf4313c2906f2800e537715192
TOACCOUNT=bc43dec69f2198fc6b08502e2d7da2efba38c8ed
HASH=""



function color(){
    if [ $1 == "green" ]; then
        echo -e "\033[32;40m=================== $2 ===================\033[0m"
    elif [ $1 == "red" ]; then
        echo -e "\033[31;40m=================== $2 ===================\033[0m"
    fi
}
# 该函数用于获取JSON中某个键的值
function get_json_value(){
    # example get_json_value "data.json" "name" # 从jaon文件中读取
    # echo $(cat "$1" | grep -Po '(?<="'$2'":")[^"\\]*(?:\\.[^"\\]*)*')
    echo $(echo "$1" | grep -Po '(?<="'$2'":")[^"\\]*(?:\\.[^"\\]*)*')
}
# 查询节点数
function get_peers() {
  color red "查询节点数 [必须开启admin]"
  curl -X POST --data '{"jsonrpc":"2.0","method":"admin_peers","params":[],"id":1}' -H "Content-Type: application/json" http://${IP}:${PORT} | jq
}
# 查询区块高度
function get_height() {
  color red "查询区块高度"
  curl --request POST \
    --url http://${IP}:${PORT}/ \
    --header 'content-type: application/json' \
    --data '{"id":1,"jsonrpc":"2.0","method":"eth_blockNumber","params":[]}'
}
# 解锁账号
function unlock_account() {
  account=$1
  color red "解锁账号 [账号只需解锁一次]"
  curl --data '{"method":"personal_unlockAccount", "params":["'"${account}"'","1", 0], "id":1, "jsonrpc":"2.0"}' -H "Content-Type: application/json" -X POST http://${IP}:${PORT}
}
# 转账
function transaction() {
  from=$1
  to=$2
  color red "发起交易"
  # 发交易; from地址是复制node0地址
  # 从该地址 0xbc43dec69f2198fc6b08502e2d7da2efba38c8ed 转账 到 0xB565a3B4a3553474205aAc1Fa1794D8A3A5A03e4
  result_json=`curl --request POST \
    --url http://${IP}:${PORT}/ \
    --header 'content-type: application/json' \
    --data '{"jsonrpc": "2.0","method": "eth_sendTransaction","params": [{"from": "'"${from}"'","to": "'"${to}"'","value": "0x100"}],"id": 1}'`
  echo "=============>result_json=$result_json"
  HASH=`get_json_value $result_json "result"`
  # # hash=get_json_value "$result_json" "result"
  echo "==================> 交易hash=$HASH"
}

function transaction_detail() {
  hash=$1
  color red "查询交易详情"
  curl -X POST \
    --data "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionByHash\",\"params\":[\"${hash}\"],\"id\":1}" \
    -H "Content-Type: application/json" \
    http://${IP}:${PORT} | jq
}

function main() {
  get_peers
  get_height
  unlock_account 0x$FROMACCOUNT
  transaction 0x$FROMACCOUNT 0x$TOACCOUNT
  transaction_detail $HASH
}
main